package org.boot.wxipad.common.util.http.apache;

import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.net.URIAuthority;
import org.boot.wxipad.common.util.http.RequestHttp;
import org.boot.wxipad.common.util.http.SimplePostRequestExecutor;

import java.io.IOException;

/**
 * @author liyuncong
 * @version 1.0
 * @file ApacheSimplePostRequestExecutor
 * @brief ApacheSimplePostRequestExecutor
 * @details ApacheSimplePostRequestExecutor
 * @date 2024-08-09
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-08-09               liyuncong          Created
 */
public class ApacheSimplePostRequestExecutor extends SimplePostRequestExecutor<CloseableHttpClient, HttpHost> {
    public ApacheSimplePostRequestExecutor(RequestHttp requestHttp) {
        super(requestHttp);
    }

    /**
     * default contentType application/json
     */
    @Override
    public String execute(String uri, String postEntity) throws IOException {

        HttpPost httpPost = new HttpPost(uri);

        HttpHost httpProxy = requestHttp.getRequestHttpProxy();
        if (httpProxy != null) {
            httpPost.setAuthority(new URIAuthority(httpProxy));
        }

        if (postEntity != null) {
            StringEntity stringEntity = new StringEntity(postEntity, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
        }

        try {
            return requestHttp.getRequestHttpClient().execute(httpPost, Utf8ResponseHandler.INSTANCE);
        } finally {
            httpPost.reset();
        }
    }
}
